//
//  ViewController.swift
//  图像性能优化
//
//  Created by YYY on 2017/10/18.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let rect = CGRect(x: 0, y: 0, width: 160, height: 160)
        
        let imageView = UIImageView(frame: rect)
        let image = UIImage(named: "水果.jpg")
        imageView.image = avatarImage(image: image!, size: rect.size, backgroundColor: view.backgroundColor)
        imageView.center = view.center
        view.addSubview(imageView)
        // Do any additional setup after loading the view, typically from a nib.
    }

    // MARK: 图像上下文
    func avatarImage(image: UIImage, size: CGSize, backgroundColor: UIColor?) -> UIImage?{
        //size 绘图大小
        //opaque 不透明度
        //scale 屏幕分辨率 0，代表使用当前设备的屏幕分辨率
        
        let rect = CGRect(origin: CGPoint(), size: size)
        //图像上下文
        UIGraphicsBeginImageContextWithOptions(size, true, 0)
        //背景填充
        backgroundColor?.setFill()
        //矩形区域填充
        UIRectFill(rect)
        //设置头像圆角 实例化一条圆形路径
        let path = UIBezierPath(ovalIn: rect)
        //对路径进行裁剪
        path.addClip()
        //绘制(在指定区域拉伸屏幕)
        image.draw(in: rect)
        //设置路径的宽度和颜色
        UIColor.darkGray.setStroke()
        path.lineWidth = 2
        path.stroke()
        //获得结果
        let result = UIGraphicsGetImageFromCurrentImageContext()
        //关闭上下文
        UIGraphicsEndImageContext()
        //返回结果
        return result
    }


}

